﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml;
using bmapi.Models.DataEntity;
using static bmapi.HelperClass.AssistFun;

namespace bmapi.Controllers
{
    public class CADMarkController : CADApplyController
    {
        [HttpPost, Route("cadMark/Apply")]
        public string Apply(int id)
        {
            //登陆者login_id
            //id实际是token 
            User user = GetUserByLoginID(GetCrrentIDByToken());
            if (user != null)
            {
                WriteDebug("CADMarkController", id.ToString());

                PC pc = null;
                if (id != 0)
                    pc = this.GetPC(id);
                else
                    pc = LockBed(user);

                if (pc == null)             
                    return ReturnOK(0, 0, "");//没有合适任务
                else
                {
                    if(id == 0)
                       AddTask(user.code, pc.pc_id);
                  
                    //检查是否有捆绑到一起的排料流程
                    List<string> names = LockBindPC(pc,user.login_id);
                    if (names == null)
                        return ReturnOK(pc.pc_id, pc.step, pc.path);
                    else
                        return ReturnMarkOK(pc.pc_id, pc.step,pc.path,names);
                }
            }
            else
            {
                return ReturnError(201, "不合法的用户");
            }
        }

        [HttpGet, Route("cadMark/FindTask")]
        public string FindTask()
        {
            //当前登录者 
            User user = GetUserByLoginID(GetCrrentIDByToken());
            return CheckIsHavePC(user).ToString();
        }


 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">流程id</param>
        /// <param name="process">工序编号</param>
        /// <param name="name">流程名</param>
        /// <param name="pod">pod文件名</param>
        /// <returns></returns>
        private string ReturnMarkOK(int id, int process,string currentNmae, List<string> names, int pod = 0)
        {
            XmlDocument doc = new XmlDocument();

            XmlNode root = doc.CreateElement("task");
            doc.AppendChild(root);

            XmlElement p = doc.CreateElement("status");
            p.InnerText = "200";
            root.AppendChild(p);

            p = doc.CreateElement("tip");
            p.InnerText = "OK";
            root.AppendChild(p);

            p = doc.CreateElement("id");
            p.InnerText = id.ToString();
            root.AppendChild(p);

            string sql = "select Model_tb.name from Model_tb join PC_tb on Model_tb.id=PC_tb.model_id where pc_id=@pcid";
            SQLCommand sc = new SQLCommand(sql, "@pcid", id);
            string modelName = sc.ExecuteScalar();
            if (modelName == null)
                modelName = "";
            p = doc.CreateElement("model");
            p.InnerText = modelName;
            root.AppendChild(p);

            p = doc.CreateElement("name");
            p.InnerText = currentNmae;
            root.AppendChild(p);

            p = doc.CreateElement("process");
            p.InnerText = process.ToString();
            root.AppendChild(p);

            p = doc.CreateElement("pod");
            p.InnerText = pod.ToString();
            root.AppendChild(p);

            p = doc.CreateElement("order");          
            for (int i = 0; i < names.Count; i++)
            {
                XmlElement str = doc.CreateElement("string");
                str.InnerText = names[i];
                p.AppendChild(str);
            }
            root.AppendChild(p);


            return ConvertXmlToString(doc);
        }

        /// <summary>
        /// 判断该流程是否有绑定 且获取绑定的所有流程名
        /// </summary>
        /// <param name="pcid"></param>
        /// <returns></returns>
        private List<string> LockBindPC(PC pc,int loginid)
        {
            List<string> pcnames = new List<string>();
            if(pc.bind_id == 0)
            {
                pcnames.Add(pc.path);
                return pcnames;
            }
            //多个生产单邦定的话, 其中有一个是主生产单,其bind_id = id,其他生产单的bind_id = 主生产单的id

            WriteDebug("GetPcNames1", pc.pc_id.ToString());
            try
            {
                //改变流程工序 
                List<SQLCommand> cmds = new List<SQLCommand>();
                string sql = "update PC_tb set download=1,station=@loginid,maxStep=@max where bind_id=@bindid";
                pc.maxStep = GetMax(pc.maxStep, pc.step);

                SQLCommand sc = new SQLCommand(sql);
                sc.Add("@loginid", loginid);
                sc.Add("@max", pc.maxStep);
                sc.Add("@bindid", pc.pc_id);

                int count = sc.ExecuteNonQuery();
                WriteDebug("GetPcNames2", "update=" + count.ToString());
                if (count > 0)
                {
                    sc = new SQLCommand("select path from PC_tb where bind_id=@bindid", "@bindid", pc.pc_id);
                    DataTable dt = sc.ExecuteScalars();
                    if (dt == null)
                        return null;
                    else
                    {
                        WriteDebug("GetPcNames3", "sql=" + dt.Rows.Count);

                        foreach (DataRow item in dt.Rows)
                            pcnames.Add(item[0].ToString());
                    }
                }
                return pcnames;
            }
            catch (Exception e)
            {
                WriteDebug("GetPcNames4", e.Message);
                return null;
            }
        }
    }
}
